package org.example.java_chatroom.api;

import org.example.java_chatroom.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.ObjectName;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author @fiber-cloud
 * @Date 2025/11/4 17:40
 */
@RestController
public class MessageSessionAPI {

    @Resource
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    @GetMapping("/sessionList")
    @ResponseBody
    public Object getMessageSessionList(HttpServletRequest req){
        List<MessageSession> messageSessionList = new ArrayList<>();


        // 1. 获取到当前用户的userId(从spring的session中获取
        HttpSession session = req.getSession(false);
        if (session == null){
            //会话并不存在,未登录
            System.out.println("[getMessageSessionList] session == null");
            return messageSessionList;
        }

        User user = (User) session.getAttribute("user");
        if (user == null){
            //user为空，说明用户不存在
            System.out.println("[getMessageSessionList] user 不存在");
            return messageSessionList;
        }

        // 2.根据userId查询数据库，查出来有哪些会话
        List<Integer> sessionIdList =  messageSessionMapper.getSessionIdByUserId(user.getUserId());
        for (int sessionId : sessionIdList){
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);

            // 3.遍历会话id，查询出每个会话里涉及到的好友都有哪些
            List<Friend> friends = messageSessionMapper.getFriendsBySessionId(sessionId, user.getUserId());
            messageSession.setFriends(friends);

            // 4.遍历会话id，查询出每个会话的最后一条消息
            String lastMessage = messageMapper.getLastMessageBySessionId(sessionId);
            //有可能出现按照会话id查不到消息的情况
            if (lastMessage == null){
                //会话中没有消息
                messageSession.setLastMessage("");
            }else {
                messageSession.setLastMessage(lastMessage);
            }

            messageSessionList.add(messageSession);
        }
        //最终目标是构造出一个MessageSession对象的数组
        return messageSessionList;
    }


    //新增一个会话
    @PostMapping("/session")
    @ResponseBody
    @Transactional
    public Object addMessageSession(int toUserId, @SessionAttribute("user") User user) {

        HashMap<String, Integer> resp = new HashMap<>();
        // 进行数据库的插入操作
        // 1. 先给 message_session 表里插入记录. 使用这个参数的目的主要是为了能够获取到会话的 sessionId
        //    换而言之, MessageSession 里的 friends 和 lastMessage 属性此处都用不上.
        MessageSession messageSession = new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);

        // 2. 给 message_session_user 表插入记录.
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(user.getUserId());
        messageSessionMapper.addMessageSessionUser(item1);

        // 3. 给 message_session_user 表插入记录.
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setSessionId(messageSession.getSessionId());
        item2.setUserId(toUserId);
        messageSessionMapper.addMessageSessionUser(item2);

        System.out.println("[addMessageSession] 新增会话成功! sessionId=" + messageSession.getSessionId()
                + " userId1=" + user.getUserId() + " userId2=" + toUserId);

        resp.put("sessionId", messageSession.getSessionId());
        // 返回的对象是一个普通对象也可以, 或者是一个 Map 也可以, jackson 都能进行处理.
        return resp;
    }
}
